<template>
	<a-card :bordered="false">
		<div class="table-page-search-wrapper">
			<a-form layout="inline">
				<a-row :gutter="48">

					<a-col :md="8" :sm="24">
						<a-form-item label="生产单号">
							<a-input v-model="queryParam.orderNumber" placeholder="请输入生产单号" />
						</a-form-item>
					</a-col>

					<a-col :md="!advanced && 8 || 24" :sm="24">
						<span class="table-page-search-submitButtons"
							:style="advanced && { float: 'right', overflow: 'hidden' } || {}">
							<a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
							<!--<a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>-->
						</span>
					</a-col>

					<a-col :md="24" :sm="24">
						<a-form-item label="归属公司：">
							<FCOrgRadioGroup v-model="queryParam.orgId" :filter-types="[$businessEnum.ORG_TYPE_ENUM.COMPANY.id]" />
							<!--              <a-radio-group default-value="" button-style="solid" v-model="queryParam.orgIdCompany">-->
							<!--                <a-radio-button value="">-->
							<!--                  全部-->
							<!--                </a-radio-button>-->
							<!--                <a-radio-button :value="id" v-for="{id, name} in orgs">-->
							<!--                  {{ name }}-->
							<!--                </a-radio-button>-->
							<!--              </a-radio-group>-->

						</a-form-item>
					</a-col>

					<a-col :md="24" :sm="24">
						<a-form-item label="是否可用：">
							<a-radio-group :default-value="null" button-style="solid" v-model="queryParam.status">
								<a-radio-button :value="null">全部</a-radio-button>
								<a-radio-button :value="0">可用</a-radio-button>
								<a-radio-button :value="1">不可用</a-radio-button>
							</a-radio-group>
						</a-form-item>
					</a-col>

				</a-row>
			</a-form>
		</div>

		<div class="table-operator">
			<template>
				<a-button type="primary" @click="handleScheduleProductionShow" v-if="hasPerm('emsOrder:doScheduleProduction')">
					排单生产
				</a-button>
				<a-button type="primary" @click="handleRecommendedProduction" v-if="hasPerm('emsOrder:recommendedProduction')">
					推荐生产
				</a-button>
				<a-button type="primary" @click="handleMaterialCalculation">物料计算</a-button>
				<a-button type="primary" @click="$refs.addForm.add({ orderType })" style="float: right;"
					v-if="hasPerm('emsOrder:addAllType')">录入
				</a-button>
				<a-button type="primary" @click="handleAddMaterialToRequisitionPool">添加到领料单池</a-button>
			</template>
		</div>

		<s-table ref="table" size="default" :columns="columns" :data="loadData" :alert="false"
			:rowKey="(record) => record.orderId"
			:rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">

			<span slot="status" slot-scope="text, record">
				<a-switch :checked="record.status == 0" :loading="record.loading"
					@change="onOrderStatusChange($event, record)" />
			</span>

			<span slot="action" slot-scope="text, record">
				<template v-if="record.isOverseasStore == 'N'">
					<a @click="$refs.editForm.disabledShow(record)">详情</a>
					<a-divider type="vertical" />
					<a @click="$refs.editForm.edit(record)">订单编辑</a>
					<a-divider type="vertical" />
					<a @click="$refs.productList.show(record,
						{ title: '产品列表', viewState: 'productionPool', materialType: $businessEnum.MATERIAL_TYPE_ENUM.product.id })">
						产品列表</a>
					<template v-if="hasPerm('emsOrder:edit')">
						<a-divider type="vertical" />
						<a-popconfirm placement="topRight" title="确认删除？" @confirm="() => del(record)">
							<a>删除</a>
						</a-popconfirm>
					</template>
				</template>
				<template v-else>
					<a @click="$refs.editForm.disabledShow(record)">详情</a>
					<a-divider type="vertical" />
					<a @click="$refs.editForm.edit(record)">订单编辑</a>
					<a-divider type="vertical" />
					<a
						@click="$refs.productList.show(record,
							{ title: '产品列表', viewState: 'productionPool', materialType: $businessEnum.MATERIAL_TYPE_ENUM.overseasProduct.id })">
						产品列表</a>
					<template v-if="hasPerm('emsOrder:edit')">

						<a-divider type="vertical" />
						<a-popconfirm placement="topRight" title="确认删除？" @confirm="() => del(record)">
							<a>删除</a>
						</a-popconfirm>
					</template>

				</template>
			</span>

		</s-table>

		<add-form ref="addForm" @ok="handleOk" />
		<edit-form ref="editForm" @ok="handleOk" />

		<!--  排单生产提示  -->
		<a-modal title="提示" :visible="scheduleProductionVisible" @ok="handleOkByScheduleProduction"
			@cancel="scheduleProductionVisible = false">
			<p>确认将选择的生产单进行排单生产吗?</p>
		</a-modal>
		<!--  推荐生产  -->
		<recommend-production ref="recommendProduction" @getTableData="getTableData" />
		<recommend-tablemodal ref="recommendTablemodal" />
		<!--  物料计算  -->
		<material-calculation-form ref="materialCalculationForm" @ok="handleOk" />
		<product-list ref="productList" />
	</a-card>
</template>

<script>
import { STable } from '@/components'
import { changeStatus, del, doScheduleProduction, page, addPicking } from '@/api/modular/main/emsorder/emsOrderManage'
import { getUrlParam } from '@/utils/util'
import FCOrgRadioGroup from '@/components/FcOrgRadioGroup/FCOrgRadioGroup'

import addForm from '@/views/main/emsorder/emsOrderAddForm'
import editForm from '@/views/main/emsorder/emsOrderEditForm'
import materialCalculationForm from '@/views/main/emsorder/emsOrderMaterialCalculationForm'
import RecommendProduction from './recommendProduction'
import RecommendTablemodal from './recommendTableModal'
import ProductList from './productList'


export default {
	components: {
		RecommendProduction,
		RecommendTablemodal,
		STable,
		addForm,
		editForm,
		materialCalculationForm,
		FCOrgRadioGroup,
		ProductList,
	},
	data() {
		return {
			advanced: false, // 高级搜索 展开/关闭
			queryParam: {},  // 查询参数
			columns: [
				{
					title: '序号', width: '80px',
					customRender: (text, record, index) => `${index + 1}`
				},
				{
					title: '生产单号',
					dataIndex: 'orderNumber'
				},
				{
					title: '归属子公司',
					dataIndex: 'targetOrgName'
				},
				{
					title: '是否可用',
					dataIndex: 'status',
					scopedSlots: { customRender: 'status' }
				},
				{
					title: '是否海外仓',
					dataIndex: 'isOverseasStore',
					customRender: (text, record, index) => record.isOverseasStore == 'Y' ? '是' : '否'
				},
				{
					title: '录入时间',
					dataIndex: 'createTime'
				},
				{
					title: '预计完成时间',
					dataIndex: 'estimateCompletionTime'
				},
				{
					title: '排序',
					dataIndex: 'sort'
				},
				{
					title: '操作',
					dataIndex: '',
					width: '280px',
					scopedSlots: { customRender: 'action' }
				}
			],
			// 加载数据方法 必须为 Promise 对象
			loadData: parameter => {
				this.queryParam.orderType = this.orderType
				this.queryParam.executeStatus = this.executeStatus
				return page(Object.assign(parameter, this.queryParam)).then((res) => {
					return res.data
				})
			},
			scheduleProductionVisible: false,
			selectedRowKeys: [],
			selectedRows: [],
			defaultExpandedKeys: [],
			replaceFields: {
				key: 'id',
			},
			urlParam: {},
			columnsType: '',
			suppliers: [],
			orgs: [],
			viewState: '',
			materialType: '',
			materialCalculationList: [],//物料计算选中的所有数据 （每页数据总计）
		}
	},
	computed: {
		orderType() {
			return this.$businessEnum.ORDER_TYPE_ENUM.produceOrder.id
		},
		executeStatus() {
			return this.$businessEnum.EXECUTE_STATUS_ENUM.DRAFT.id
		},
	},
	methods: {
		del(record) {
			del(record).then((res) => {
				if (res.success) {
					this.$message.success('删除成功')
					this.$refs.table.refresh()
				} else {
					this.$message.error('删除失败：' + res.message)
				}
			}).catch((err) => {
				this.$message.error('删除错误：' + err.message)
			})
		},
		toggleAdvanced() {
			this.advanced = !this.advanced
		},
		handleOk() {
			this.$refs.table.refresh()
			this.$refs.table.clearSelected()
		},
		onSelectChange(selectedRowKeys, selectedRows) {
			// selectedRowKeys.forEach(val => {
			// 	if (!this.materialCalculationList.includes(val)) {
			// 		this.materialCalculationList.push(val);
			// 	} else {

			// 	}
			// })
			this.selectedRowKeys = selectedRowKeys
			this.selectedRows = selectedRows
		},
		onOrderStatusChange(checked, row) {
			row.loading = true
			let { orderId } = row
			let status = checked ? 0 : 1
			let parameter = { orderId, status }
			changeStatus(parameter).then(res => {
				this.handleOk()
			})
		},
		/**
		 * 添加到领料单池
		 */
		handleAddMaterialToRequisitionPool() {
			if (this.validateAddMaterialToRequisitionPool()) {
				let orderIds = this.selectedRowKeys;
				addPicking({
					orderIds: orderIds,
					isAddPicking: 2
				}).then(res => {
					console.log(res);
					if (res.code == 200) {
						this.selectedRowKeys = [];
						this.selectedRows = [];
						this.$refs.table.refresh();
						this.$refs.table.updateSelect(this.selectedRowKeys, this.selectedRows);
						this.$message.success('添加成功');
					}
				})
			}
		},
		validateAddMaterialToRequisitionPool() {
			let selectedRows = this.selectedRows
			if (selectedRows.length == 0) {
				this.$message.error('请先选择要添加订单')
				return false
			}
			let unavailableOrders = selectedRows.filter(value => value.status != 0)
			if (unavailableOrders.length > 0) {
				this.$message.error('订单状态必须为"可用"才可以进行添加')
				return false
			}
			let unavailableOrders1 = selectedRows.filter(value => value.isAddPicking != 1);
			console.log(unavailableOrders1, "unavailableOrders1");

			if (unavailableOrders1.length > 0) {
				this.$message.error('选择的订单已经存在领料单池中')
				return false
			}
			return true
		},
		// 排单生产
		handleScheduleProductionShow() {
			if (this.validateScheduleProduction()) {
				this.scheduleProductionVisible = true
			}
		},
		validateScheduleProduction() {
			let selectedRows = this.selectedRows
			if (selectedRows.length == 0) {
				this.$message.error('请先选择要排单生产的订单')
				return false
			}
			let unavailableOrders = selectedRows.filter(value => value.status != 0)
			if (unavailableOrders.length > 0) {
				this.$message.error('订单状态必须为"可用"才可以进行排单')
				return false
			}
			return true
		},
		handleOkByScheduleProduction() {
			// 调接口,排单生产
			if (this.validateScheduleProduction()) {
				let orderIds = this.selectedRows.map(value => value.orderId).join(',')
				doScheduleProduction({ orderIds }).then(res => {
					this.$message.success(res.message)
					this.scheduleProductionVisible = false
					this.handleOk()
				})
			}
		},
		getTableData(value) {
			console.log("子组件传来的列表数据", value)
			// 将数据传给新的弹框
			this.$refs.recommendTablemodal.show({
				selectedList: this.selectedRows,
				value: value.data,
				beforeNum: value.beforeNum
			})
		},
		handleRecommendedProduction() {
			// 推荐生产
			if (this.selectedRows.length < 2) {
				this.$message.error('请至少选择两条生产单')
				return
			}

			let parameter = this.selectedRows
			this.$refs.recommendProduction.show(parameter)
		},
		handleMaterialCalculation() {
			// pb物料计算			
			let orderIds = this.selectedRowKeys.join(',')
			if (orderIds == '') {
				this.$message.error('请先选择订单')
				return
			}
			this.$refs.materialCalculationForm.add(orderIds)
		},
	}
}
</script>

<style lang="less">
.table-operator {
	margin-bottom: 18px;
}

button {
	margin-right: 8px;
}
</style>
